﻿using System;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using net.xBei.Helper;
using net.xBei.WebApi.Configurations;

namespace net.xBei.WebApi.Helper {
    /// <summary>
    /// 加载配置
    /// </summary>
    public static class ConfigurationHelper {
        /// <summary>
        /// 从配置文件中获取值
        /// </summary>
        /// <typeparam name="TSettings"></typeparam>
        /// <param name="configuration"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static TSettings GetSettings<TSettings>(this IConfiguration configuration, string key)
            => configuration.GetSection(key).Get<TSettings>();
        /// <summary>
        /// 从配置文件中获取值
        /// </summary>
        /// <typeparam name="TSettings"></typeparam>
        /// <param name="app"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static TSettings GetSettings<TSettings>(this Microsoft.AspNetCore.Builder.WebApplication app, string key)
            => GetSettings<TSettings>(app.Configuration, key);
        /// <summary>
        /// 从配置文件中获取值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="configuration"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static T? GetValueByPath<T>(this IConfiguration configuration, string path) {
            if (!path.Contains('.')) {
                return configuration.GetValue<T>(path);
            }
            var paths = path.Split(".");
            return GetValueByPath<T>(configuration.GetSection(paths[0]), paths.Skip(1).JoinBy('.'));
        }
        /// <summary>
        /// 开始批量配置
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static (IServiceCollection, IConfiguration) SetupConfigurations(this IServiceCollection services, IConfiguration configuration) {
            return (services, configuration);
        }
        /// <summary>
        /// 注册配置
        /// </summary>
        /// <typeparam name="Settings"></typeparam>
        /// <param name="inc"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static (IServiceCollection, IConfiguration) Configure<Settings>(this (IServiceCollection services, IConfiguration configuration) inc)
            where Settings : class, IAutoLoadConfigurations {
            var type = typeof(Settings);
            var attr = type.GetCustomAttribute<AutoLoadConfigurationsAttribute>();
            inc.services.Configure<Settings>(inc.configuration.GetSection(attr?.SectionName?? type.Name));
            return inc;
        }
    }
}
